#include<stdio.h>
#include<at89c51ed2.h>
#include<mcs51reg.h>
#include<stdlib.h>
#include "spi.h"
#include "io.h"
#include "eeprom.h"
#include "glcd.h"
#include "graphics.h"

/**************************************************************************/
#define RadioSlaveSelect P1_3
#define Control 		0x03
#define SERDESCtrl 		0x06
#define TxSERDESValid 	0x10
#define AnalogCtrl 		0x20
#define Channel		 	0x21
#define PABias	 		0x23
#define XtalAdjust	 	0x24
#define VCOCalibration 	0x26
#define RegPwrCtrl 		0x2E
#define CarrierDetect 	0x2F
#define ClockManual 	0x32
#define ClockEnable 	0x33

#define SynthesizerSettle 200
#define RxReady 		  60
#define ADCDelay 		  100
#define baseFreq		0x02


/**************************************************************************/





void delay(int time){
	while(time>0){
		time--;
	}
}

void singleWrite(int addr,int cmd)__critical
{
	unsigned char ack;
	
	addr|=0x80;
	P1_3=0;  /*slave select*/
	ack=spi_dataSend(addr); /*send command*/
	
	if(ack==0){
		printf("Write failed!!\n\r");
	}
	delay(10);
	ack=spi_dataSend(cmd); /*send register address */
	if(ack==0){
		printf("Write failed!!\n\r");
	}
	
	
	P1_3=1;  /*slave select*/
}


void chipInit()
{
	
	 i2cexpanderWrite(0x3F);
	 delay(4);
	 i2cexpanderWrite(0x7F);
	 
	
	
	singleWrite(AnalogCtrl,0x45);
	
	singleWrite(AnalogCtrl,0x44);
	
	singleWrite(RegPwrCtrl,0x80);
	
	singleWrite(VCOCalibration,0xC0);
	
	singleWrite(ClockEnable,0x41);
	
	singleWrite(ClockManual,0x41);
	
	singleWrite(XtalAdjust,0x40);
	
	singleWrite(SERDESCtrl,0x09);
	
	
	singleWrite(TxSERDESValid ,0xFF);
	
	
	singleWrite(PABias,0x05);
	 i2cexpanderWrite(0xFF);
	
}


	
	
 	
 	
	
	
int rssiRead(int freqOffset)
{
	unsigned char RSSI;
	unsigned char i;
	unsigned char MaxRSSI;


	
	MaxRSSI=0;
	for(i=0;i<10;i++){
	
	
	
	readAgain:
	singleWrite(Control,0x00);/*disable receiver mode*/
	singleWrite(Control,0x90);/*enable receiver mode*/
	singleWrite(Channel,freqOffset); /*set the required channel frequency*/
	
	

	
	delay(SynthesizerSettle);
	delay(RxReady);
	delay(ADCDelay );
	
	


	
	singleWrite(CarrierDetect,0x00); /*clear carrier detect*/
	singleWrite(CarrierDetect,0x80); /*this forces device to carrier detect*/

	delay(ADCDelay );
	
 	
 	RSSI=spi_dataRead(0x22,1);
 	if((RSSI&0x20)!=0x20)
 	{
 		printf("RSSI:%x\n\r",RSSI);
 		printf("in while loop");
 		goto readAgain;
 	}      

 	
 	singleWrite(CarrierDetect,0x00); /*clear carrier detect*/
 
 	
 	RSSI&=0x1F;

 	//printf("RSSI:%d\n\r",RSSI);
 	
 	if(RSSI>MaxRSSI){
 		MaxRSSI=RSSI;
 		
 	}
	
 	
	}

 	//printf("%d\n\r",MaxRSSI);
 
 	return MaxRSSI;
}

/***********************************************************************/
